﻿using RMS.EF.Model;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Dynamic;
using System.Text;
using System.Threading.Tasks;
using RMS.Common;

namespace RMS.BLL
{
    public class ConfigBll
    {
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="model">新增的模型实体</param>
        /// <returns></returns>
        public CommonOutPutVm Add(RMS_Config model)
        {
            var result = new CommonOutPutVm();
            #region 输入验证
            var errdic = model.Validate();
            if (errdic != null)
            {
                result.ErrorDic = errdic;
                return result;
            } 
            #endregion
            #region 默认值赋值
            var now = DateTime.Now;
            model.Id = Guid.NewGuid().ToString();
            model.EDeleted = E_Deleted.Normal;
            model.CreationTime = now;
            model.CreationUser = model.LastUpdateUser;
            model.LastUpdateTime = now; 
            #endregion
            using (var db = new RMSEntities())
            {
                #region 存在验证
                bool exist = db.RMS_Config.AsNoTracking().Any(p => p.Deleted == (int)E_Deleted.Normal && p.Id != model.Id && (p.Key == model.Key));
                if (exist)
                {
                    result.Message = "键已经存在";
                    return result;
                }
                #endregion
                #region 保存
                db.RMS_Config.Add(model);
                int row = db.SaveChanges();
                if (row != 1)
                {
                    result.Message = "新增配置保存异常：" + model.Id;
                    return result;
                }
                #endregion
            }
            result.IsSuccess = true;
            result.Message = "保存成功";
            return result;
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="model">修改后的模型实体</param>
        /// <returns></returns>
        public CommonOutPutVm Updata(RMS_Config model)
        {
            var result = new CommonOutPutVm();
            #region 输入验证
            var errdic = model.Validate();
            if (errdic != null)
            {
                result.ErrorDic = errdic;
                return result;
            }
            #endregion
            #region 默认值赋值
            model.LastUpdateTime = DateTime.Now; 
            #endregion
            using (var db = new RMSEntities())
            {
                #region 存在验证
                bool exist = db.RMS_Config.AsNoTracking().Any(p => p.Deleted == (int)E_Deleted.Normal && p.Id != model.Id && (p.Key == model.Key));
                if (exist)
                {
                    result.Message = "键已经存在";
                    return result;
                }
                #endregion
                #region 保存
                db.Entry(model).State = EntityState.Modified;
                db.Entry(model).Property(p => p.Deleted).IsModified = false;
                db.Entry(model).Property(p => p.CreationTime).IsModified = false;
                db.Entry(model).Property(p => p.CreationUser).IsModified = false;
                int row = db.SaveChanges();
                if (row != 1)
                {
                    result.Message = "修改配置保存异常：" + model.Id;
                    return result;
                }
                #endregion
            }
            result.IsSuccess = true;
            result.Message = "保存成功";
            return result;
        }
        /// <summary>
        /// 软删除
        /// </summary>
        /// <param name="id">数据Id字符串","分隔</param>
        /// <returns></returns>
        public CommonOutPutVm Delete(string id)
        {
            CommonOutPutVm result = new CommonOutPutVm();
            #region 验证
            if (string.IsNullOrWhiteSpace(id))
            {
                result.Message = "请选择一条数据";
                return result;
            }
            #endregion
            #region 删除
            using (var db = new RMSEntities())
            {
                db.Database.ExecuteSqlCommand("update RMS_Config set Deleted=1 where Id in ('" + id + "')");
                db.SaveChanges();
            }
            #endregion
            result.IsSuccess = true;
            result.Message = "删除成功";
            return result;
        }
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="page">分页参数</param>
        /// <returns></returns>
        public CommonOutPutVm GetByPage(PageParamsT<S_RMS_Config> page)
        {
            var result = new CommonOutPutVm();
            using (var db = new RMSEntities())
            {
                var q = db.RMS_Config.Where(p => p.Deleted == (int)E_Deleted.Normal);
                #region where
                if (!string.IsNullOrWhiteSpace(page.SearchModel.SearchValue))
                {
                    q = q.Where(p => p.Key.Contains(page.SearchModel.SearchValue) || p.Description.Contains(page.SearchModel.SearchValue));
                }
                if (page.SearchModel.Status != E_Status.All)
                {
                    q = q.Where(p => p.Status == (int)page.SearchModel.Status);
                }
                #endregion
                page.Total = q.Count();
                #region order by
                if (string.IsNullOrWhiteSpace(page.Order))
                {
                    q = q.OrderBy(p => p.Key);
                }
                else
                {
                    var orderExpression = string.Format("{0} {1}", page.Order, page.OrderType);
                    q = q.OrderBy(orderExpression);
                }
                #endregion
                q = q.Skip(page.Start).Take(page.Length);
                result.Data = q.ToList();
            }
            result.IsSuccess = true;
            return result;
        }
        /// <summary>
        /// 根据Id获取未删除的实体
        /// </summary>
        /// <param name="id">Id主键</param>
        /// <returns></returns>
        public CommonOutPutVm GetById(string id)
        {
            var result = new CommonOutPutVm();
            using (var db = new RMSEntities())
            {
                var data = db.RMS_Config.AsNoTracking().FirstOrDefault(p => p.Id == id && p.Deleted == (int)E_Deleted.Normal);
                if (data == null)
                {
                    result.Message = "配置不存在";
                    return result;
                }
                result.Data = data;//EntityHelper.ConverToTEntity<RMS_Config_Extend>(data);
            }
            result.IsSuccess = true;
            return result;
        }
        /// <summary>
        /// 根据配置键获取可用配置项
        /// </summary>
        /// <param name="key">配置键</param>
        /// <returns></returns>
        public CommonOutPutVm GetEnableByKey(string key)
        {
            var result = new CommonOutPutVm() { Data = string.Empty };
            #region 输入验证
            if (string.IsNullOrWhiteSpace(key))
            {
                result.Message = "请输入Key";
                return result;
            }
            #endregion
            using (var db = new RMSEntities())
            {
                var data = db.RMS_Config.AsNoTracking().FirstOrDefault(p => p.Key == key && p.Deleted == (int)E_Deleted.Normal && p.Status == (int)E_Status.Enable);
                #region 存在验证
                if (data == null)
                {
                    result.Message = "配置不存在";
                    return result;
                }
                #endregion
                result.Data = data.Value;
            }
            result.IsSuccess = true;
            result.Message = "获取成功";
            return result;
        }
    }
}
